package com.ug.config.filter;

import com.ug.common.utils.JwtUtil;
import com.ug.common.utils.StringUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @Author LY
 * @create 2024/7/16 17:10
 * @Description 拦截校验token
 */
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthorizationFilter.class);

    /**
     * 过滤用户请求
     * @param request 请求
     * @param response 响应
     * @param filterChain 过滤
     */
    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                                    @NonNull FilterChain filterChain) throws ServletException, IOException {
        try {
            logger.info("请求路径:{}", request.getRequestURI());
            //  从request中获取token
            String token = JwtUtil.token();
            //  如果token不存在或者携带了刷新token(长度小于150,可以根据自己生成的refreshToken来判断),
            //  直接放行,由系统Security判断是否具有访问权限
            if (StringUtil.isBlank(token) || token.length() < 150){
                filterChain.doFilter(request, response);
                return;
            }
            //  校验token是否有效
            if (JwtUtil.verifyToken(token)){
                //  获取认证信息
                Authentication authentication = JwtUtil.getAuthentication(token);
                //  将认证信息保存在spring安全上下文中
                SecurityContextHolder.getContext().setAuthentication(authentication);
                //  放行请求
                filterChain.doFilter(request, response);
            }
        } catch (Exception e) {
            logger.error("访问异常：{}", e);
            //  token问题,统一作401处理
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
    }

}
